package controller;

import dao.TagJpaController;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import dao.exceptions.NonexistentEntityException;
import model.Tag;
import pagecontroller.JsfUtil;

/**
 *
 * @author Edilson Fernandes da Costa
 * @version 1.0
 */
public class TagController {

    public TagController() {
        if (JsfUtil.getObjectFromSession("TagJpaController") == null) {
            jpaController = new TagJpaController();
        } else {
            jpaController = (TagJpaController) JsfUtil.getObjectFromSession("TagJpaController");
        }
    }
    private Tag tag = null;
    private Tag tagAux = null;
    private TagJpaController jpaController = null;
    private List<Tag> tags = null;


   public void persiste() {
        if (tag.getId() == null) {
            create();
        } else {
            update();
        }
    }

    public String update() {
        try {
            jpaController.edit(this.tag);
            tagAux = tag;
            this.tag = null;
            JsfUtil.addSuccessMessage("Tag Atualizado com Sucesso");
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(TagController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(TagController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "refreshPage";
    }

    public String create() {
        try {
            jpaController.create(tag);
            tagAux = tag;
            tag = null;
            JsfUtil.addSuccessMessage("Tag cadastrado com sucesso.");
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "Ocorreu um erro na percistencia dos dados.");
            return null;
        }
        return "refreshPage";
    }

    public String edit() {
        Tag tagTemp = (Tag) JsfUtil.getObjectFromRequestParameter("tag");
        this.tag = tagTemp;
        return "refreshPage";
    }

    public String destroy() {
        Tag tagTemp = (Tag) JsfUtil.getObjectFromRequestParameter("tag");
        try {
            jpaController.destroy(tagTemp.getId());
            JsfUtil.addSuccessMessage("Tag removido com sucesso.");
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(TagController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return "refreshPage";
    }


    public Tag getTag() {
        if (tag == null) {
            tag = new Tag();
        }
        return tag;
    }

    public List<Tag> getTags(){
        this.tags = jpaController.findTagEntities();
        return this.tags;
    }

    public TagJpaController getJpaController() {
        return jpaController;
    }

    public Tag getTagAux() {
        return tagAux;
    }


}
